<?php
$loader->requireOnce('includes/inPatientCore/InPatientCoreErrorCode.class.php');
$loader->requireOnce('includes/inPatientCore/InPatientCoreException.class.php');
/**
 * electronic medical record for inpatient.
 * @package core.ordo
 * @author hdviet
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class InPatientEmr extends ORDataObject {

	/**#@+
	 * Fields of table: in_patient_emr mapped to class members
	 */
	var $in_patient_emr_id		= '';
	var $doctor_id		= '';
	var $diagnosis		= '';
	var $icd10_primary		= '';
	var $icd10_secondary		= '';
	var $ticket_id		= '';
	var $enum_treatment_result = '';

	/**#@-*/


	/**
	 * DB Table
	 */
	var $_table = 'in_patient_emr';

	/**
	 * Primary Key
	 */
	var $_key = 'in_patient_emr_id';

	/**
	 * Internal Name
	 */
	var $_internalName = 'InPatientEmr';

	/**
	 * Handle instantiation
	 */
	function __construct() {
		parent::ORDataObject();
	}
	/**
	 * Get emr info of given ticketId
	 * @param $ticketId
	 * @return array(icd10_id,in_patient_emr_id, doctor_name, diagnosis, icd10_primary,
	 *  icd10_secondary, enum_treatment_result)
	 * <br>
	 * null : if not found.
	 */
	public function getEmrInfo($ticketId) {
		$field    =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
        
		$ds = new Datasource_sql();
		$sql = array(
            'cols'  => "in_patient_emr_id, PE.name doctor_name, IPE.doctor_id doctor_id , diagnosis,
             IC.icd10_id, IC.code icd10_p_code, IC.$field icd10_p_name,
             IC1.icd10_id s_icd10_id, IC1.code icd10_s_code, IC1.$field icd10_s_name, enum_treatment_result",
            'from'  => " in_patient_emr IPE " .                                        
                    " LEFT JOIN person PE ON IPE.doctor_id = PE.person_id 
                      LEFT JOIN icd10 IC ON icd10_primary = IC.code                       
                      LEFT JOIN icd10 IC1 ON icd10_secondary = IC1.code                      
                      ",
            'where' => "IPE.ticket_id = $ticketId"
		);
		$ds->setup($this->_db, $sql);
		$result = $ds->toArray();  
		if (empty($result)) {
			return null;
		}     
        return $result[0];
	}
	/**
	 * Create new or update emr info.
	 * <br>
	 * if not found $data['ticket_id'] then create new.
	 * <br>
	 * found then update.
	 * @param $data array of data need tobe updated. 
	 * array(doctor_id,diagnosis,icd10_primary,icd10_secondary,ticket_id, enum_treatment_result )
	 * @return nothing.
	 */
	public function recordEmrInfo($data = array()) {
		if (!isset($data['ticket_id'])) {
			throw new InpatientCoreException("lack of ticketId");
		}
		$ticketId = $data['ticket_id'];
		$emrInfo = $this->getEmrInfo($ticketId);
		
		if ($emrInfo != null) {
			// update
			$this->setup($emrInfo['in_patient_emr_id']);
		} else {
			//add new
			$this->set_id('');			
		}
	   
	   $this->populateArray($data);        
       $this->persist();	
       return $this->get_id();	
		
	}


}
?>
